package org.osomit.sacct.session.token.impl;

import org.osomit.sacct.session.token.iface.TokenIdGenerator;
import org.osomit.sacct.session.token.iface.RandomStringGenerator;
import org.osomit.sacct.server.config.iface.ServerConfig;
import com.google.inject.Inject;

/**
 * @author Jian Fang (John.Jian.Fang@gmail.com)
 *
 * Date: Jul 1, 2009
 */
public class TokenIdGeneratorImpl implements TokenIdGenerator {

    private ServerConfig config;

    private RandomStringGenerator rsGenerator;

    private Long count = new Long(0);

    public ServerConfig getConfig() {
        return config;
    }

    @Inject
    public void setConfig(ServerConfig config) {
        this.config = config;
    }

    public RandomStringGenerator getRsGenerator() {
        return rsGenerator;
    }

    @Inject
    public void setRsGenerator(RandomStringGenerator rsGenerator) {
        this.rsGenerator = rsGenerator;
    }

    protected long getCount(){
         synchronized(this.count){
           return (++count)%10;
         }
    }
    public String getNewTokenId(String prefix) {
        final StringBuffer sb = new StringBuffer();

        long timestamp = System.currentTimeMillis();
        sb.append(prefix);
        sb.append("-");
        sb.append(timestamp);
        sb.append("-");
        sb.append(this.rsGenerator.getNewString(this.config.getRandomIdLength()));
        sb.append("-");
        sb.append(this.getCount());

        return sb.toString();
    }
}
